package com.gitee.magic.framework.base.rest;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.gitee.magic.core.exception.ApplicationException;

/**
 * @author start
 */
public class HttpSsl {
	
	public static final String HTTPS_PROTOCOL_TLSV12="TLSv1.2";
	public static final String HTTPS_PROTOCOL_SSL="SSL";
	
	public static void setDefaultHttps() {
		setDefaultHttps(HTTPS_PROTOCOL_TLSV12);
	}
	
	public static void setDefaultHttpsSsl() {
		setDefaultHttps(HTTPS_PROTOCOL_SSL);
	}

	/**
	 * 访问Https优先设置,调用前设置
	 * @param protocol
	 */
	public static void setDefaultHttps(String protocol) {
		SSLContext sslCtx = null;
		try {
			sslCtx = SSLContext.getInstance(protocol);
		} catch (NoSuchAlgorithmException e) {
			throw new ApplicationException(e);
		}
		TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new XtManager();
        trustAllCerts[0] = tm;
		try {
			sslCtx.init(null, trustAllCerts, new SecureRandom());
		} catch (KeyManagementException e) {
			throw new ApplicationException(e);
		}
		//设置不验证主机
		HttpsURLConnection.setDefaultHostnameVerifier((urlHostName, session) -> true);
		HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
	}
	
    static class XtManager implements TrustManager, X509TrustManager {
    	
		@Override
	    public X509Certificate[] getAcceptedIssuers() {
	        return null;
	    }
	 
	    public boolean isServerTrusted(X509Certificate[] certs) {
	        return true;
	    }
	 
	    public boolean isClientTrusted(X509Certificate[] certs) {
	        return true;
	    }

		@Override
	    public void checkServerTrusted(X509Certificate[] certs, String authType)
	    throws CertificateException {
	        return;
	    }

		@Override
	    public void checkClientTrusted(X509Certificate[] certs, String authType)
	    throws CertificateException {
	        return;
	    }
	}
	
}
